package com.castle.releasedemo;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.castle.utils.Rsa2SignUtils;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 公钥私钥签名示例 GET请求
 * 私钥加密 公钥解密
 * @author openapi
 */
public class RsaSignGetDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String paramEncryptKey="参数秘钥(自己设置的16位秘钥)";
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, paramEncryptKey.getBytes());
        //该接口需要的私钥
        String privateKey = "下载的秘钥文件中的私钥，直接复制到此处即可";
        //用户中心-账号信息-APPID
        String appId="用户信息的APPID";


        String datetime = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
        System.out.println(datetime);
        // 请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("C-Date", datetime);
        headers.put("C-Appid", appId);
        headers.put("C-Serial", "");//此处自行生成唯一的流水号标识  本次请求的流水号（请求的唯一标识），不参与签名
        //支持 application/json 与 multipart/form-data
        headers.put("Content-Type", "application/json;charset=utf-8");

        // 查询参数 根据实际情况调整
        Map<String, String> queryParams = new HashMap<>();
//        queryParams.put("city","朝阳");
//        queryParams.put("needday","1");
//        queryParams.put("prov","北京");

        //构造签名参数字符串
        Map<String,Object> signMap=new HashMap<>();
        signMap.putAll(queryParams);
        signMap.put("cDate",datetime);
        String signString=Rsa2SignUtils.initParamMap(signMap);

        // 签名
        String sign = Rsa2SignUtils.sign(privateKey,signString);
        headers.put("Sign",sign);

        // 接口的url地址
        StringBuilder url = new StringBuilder("API接口地址");

        //拼接queryParam
        if(!queryParams.isEmpty()){
            url.append("?");
            for(String paramKey:queryParams.keySet()){
                url.append(paramKey+"="+aes.encryptHex(queryParams.get(paramKey))+"&");
            }
        }
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        Request.Builder requestBuilder=new Request.Builder().url(url.toString());
        for(String headerKey:headers.keySet()){
            requestBuilder.addHeader(headerKey,headers.get(headerKey));
        }
        Request request=requestBuilder.build();
        try {
            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
